<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form ref="form" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="应用分类" prop="type">
          <el-col :span="10">
            <select-page
              @page-change="getCategoryList"
              :optionSource="categoryList"
              v-model="form.categoryId"
              labelKey="name"
              valueKey="id"
              :paginationOption="queryParams"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="应用名称" prop="name">
          <el-col :span="10">
            <el-input v-model="form.name" placeholder="请输入名称" />
          </el-col>
        </el-form-item>
        <el-form-item label="应用简称" prop="appShort">
          <el-col :span="10">
            <el-input :disabled="ds" v-model="form.appShort" placeholder="请输入应用简称" />
          </el-col>
        </el-form-item>
        <el-form-item label="应用logo" prop="thumbnail">
          <el-col :span="10">
            <imageUpload v-model="form.logo" :limit="1" :uploadType="1"/>
          </el-col>
        </el-form-item>
        <el-form-item label="缩率图" prop="thumbnail">
          <el-col :span="10">
            <imageUpload v-model="form.thumbnail" :limit="5" :uploadType="1"/>
          </el-col>
        </el-form-item>
        <el-form-item label="版本号" prop="version">
          <el-col :span="10">
            <el-input v-model="form.record.sn" placeholder="请输入应用版本号" />
          </el-col>
        </el-form-item>
        <el-form-item label="应用秘钥" prop="secret">
          <el-col :span="10">
            <el-input v-model="form.record.secret" placeholder="请输入应用秘钥" />
          </el-col>
        </el-form-item>
        <el-form-item label="版本类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择版本类型">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.APP_MARKET_VERSION_TYPE)"
                       :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否发布" prop="release">
          <el-select v-model="form.record.release" placeholder="请选择是否发布" clearable size="small">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.SYS_WHETHER_TYPE)"
                       :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="更新内容">
          <editor v-model="form.record.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="安装包">
          <el-col :span="10">
            <el-upload v-if="!uploaded" ref="upload" :limit="1" accept=".jar" :auto-upload="false" drag
                       :headers="upload.headers" :action="upload.url" :data="upload.data" :disabled="upload.isUploading"
                       :on-change="handleFileChange"
                       :on-progress="handleFileUploadProgress"
                       :on-success="handleFileSuccess">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或 <em>点击上传</em>
              </div>
              <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入 jar 格式文件！</div>
            </el-upload>
            <el-alert
              v-else
              :title="`${this.upload.data.name}上传成功`"
              type="success">
            </el-alert>
            <el-button v-if="!uploaded" style="margin-top: 5px;" type="primary" @click="handleUpload">确认上传</el-button>
            <el-button v-else style="margin-top: 5px;" type="primary" @click="handleReUpload">重新上传</el-button>
          </el-col>
        </el-form-item>
        <el-form-item label="售价" prop="price">
          <el-col :span="10">
            <el-input v-model="form.price" placeholder="请输入售价" />
          </el-col>
        </el-form-item>
        <el-form-item label="适用平台" prop="platform">
          <el-col :span="10">
            <el-checkbox-group v-model="form.platform">
              <el-checkbox :label="dict.value" :key="dict.value" v-for="dict in platformDatas">{{dict.label}}</el-checkbox>
            </el-checkbox-group>
          </el-col>
        </el-form-item>
        <el-form-item label="是否加密" prop="encrypt">
          <el-col :span="10">
            <el-radio-group v-model="form.encrypt">
              <el-radio v-for="dict in encryptDictDatas"
                        :key="dict.value" :label="dict.value" :value="dict.value">{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item label="是否显示" prop="visible">
          <el-col :span="10">
            <el-radio-group v-model="form.visible">
              <el-radio v-for="dict in visibleDictDatas"
                        :key="dict.value" :label="dict.value" :value="dict.value">{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in statusDictDatas" :key="parseInt(dict.value)" :label="parseInt(dict.value)">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label-width="0" class="text-center mt20">
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getApp,createApp,updateApp,checkAppShortIsExist } from "@/api/product/market";
import Editor from '@/components/Editor';
import {getAccessToken} from "@/utils/auth";
import {DICT_TYPE, getDictDataLabel, getDictDatas} from "@/utils/dict";
import {isNotEmpty,isEmpty} from "@/utils/ruoyi";
import ImageUpload from "@/components/ImageUpload";
import {getMgAppMarketCategoryPage, updateMgAppMarketCategory} from "@/api/product/category";
import SelectPage from '@/components/SelectPage'
export default {
  name: "AppMarket",
  components: {
    Editor,
    ImageUpload,
    SelectPage
  },
  data() {
    return {
      id:'',
      ds:false,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        name: null,
        visible: null,
        lesseeId: null,
        status: null,
        createTime: [],
      },
      categoryList:[],
      // 表单参数
      form: {
        name:'',
        thumbnail:'',
        logo:'',
        platform:[],
        encrypt:'0',
        visible:'0',
        status:0,
        price:'',
        secrecy:'',
        record:{
          id:'',
          content:'',
          fid:'',
          downloadUrl:'',
          sn:'',
          type:'',
        }
      },
      // 表单校验
      rules: {
        categoryId: [{ required: true, message: "分类不能为空", trigger: "blur" }],
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        thumbnail: [{ required: true, message: "缩率图不能为空", trigger: "blur" }],
        appShort: [{ required: true, message: "应用简称不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if(this.ds){
                callback();
              }else {
                checkAppShortIsExist(value).then(res => {
                  const flag = res.data;
                  if (flag) {
                    callback('应用简称已存在');
                  } else {
                    callback();
                  }
                });
              }
            },
            trigger: 'blur'
          }
        ],
        logo: [{ required: true, message: "应用logo不能为空", trigger: "blur" }],
        visible: [{ required: true, message: "是否显示不能为空", trigger: "blur" }],
        platform: [{ required: true, message: "适用平台不能为空", trigger: "blur" }],
        'record.sn': [{ required: true, message: "版本号不能为空", trigger: "blur" }],
        'record.content': [{ required: true, message: "内容不能为空", trigger: "blur" }],
        encrypt: [{ required: true, message: "是否加密不能为空", trigger: "blur" }],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
      },
      //是否已上传
      uploaded:false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getAccessToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/admin-api/mg/app-market-manage/upload", // 请求地址
        data:{
          fid:undefined,
          name:'',
        },
      },
      platformDatas: getDictDatas(DICT_TYPE.APP_MARKT_PLATFORM),
      encryptDictDatas: getDictDatas(DICT_TYPE.APP_MARKT_ENCRYPT),
      visibleDictDatas: getDictDatas(DICT_TYPE.SYS_COMMON_VISIBLE),
      // 数据字典
      statusDictDatas: getDictDatas(DICT_TYPE.SYS_COMMON_STATUS)
    };
  },
  created() {
    this.getCategoryList();
    if (this.$route.query.id) {
      this.id =  this.$route.query.id;
      this.ds = true;
      this.getInfo();
    }
  },
  methods: {
    getCategoryList(val) {
      // 执行查询
      this.queryParams.pageNo = val;
      getMgAppMarketCategoryPage(this.queryParams).then(response => {
        this.categoryList = response.data.list;
        this.queryParams.total = response.data.total;
      });
    },
    getInfo(){
      getApp(this.id).then(response => {
        this.form = response.data;
        this.form.visible = this.form.visible + '';
        this.form.encrypt = this.form.encrypt + '';
        this.form.categoryId = this.form.categoryId * 1;
        debugger
        if(isNotEmpty(this.form.record.fid)){
          this.uploaded = true;
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateApp(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({ path: '/product/apps'});
          });
          return;
        }
        if(isEmpty(this.form.record.fid)){
          this.$modal.msgError("应用文件ID不能为空");
          return;
        }
        // 添加的提交
        createApp(this.form).then(response => {
          this.form.id = response.data.id;
          this.$refs.upload.submit();
          this.$modal.msgSuccess("新增成功");
          this.$store.dispatch("tagsView/delView", this.$route);
          this.$router.push({ path: '/product/apps'});
        });
      });
    },
    /** 处理上传的文件发生变化 */
    handleFileChange(file, fileList) {
      this.upload.data.path = file.name;
    },
    /** 处理文件上传中 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true; // 禁止修改
    },
    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      // 清理
      this.uploaded = true;
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.form.record.downloadUrl = response.data.url;
      debugger
      this.form.record.fid = response.data.fid;
      // 提示成功，并刷新
      this.$modal.msgSuccess("上传成功");
    },
    handleUpload(){
      this.$refs.upload.submit();
    },
    handleReUpload(){
      this.uploaded = false;
    }
  }
};
</script>
